package com.lishiots.cloud.datacenter.middleware.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import com.lishiots.cloud.datacenter.middleware.common.FileUtils;
import com.lishiots.cloud.datacenter.middleware.service.MaterialService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Chaofan at 2018-11-22 15:54
 * email:chaofan2685@qq.com
 **/
@Service
public class MaterialServiceImpl implements MaterialService {

    @Value(value = "${dc.oss.invokingRoot}")
    private String invokingRoot;

    @Value(value = "${dc.oss.root}")
    private String root;

    @Value(value = "${dc.oss.rootPath}")
    private String rootPath;


    @Override
    public Map<String, Object> addFiles(MultipartFile multpFile) {
        Map<String,Object> result = new HashMap<>();
        if (multpFile==null){
            result.put("status","1");
            result.put("msg","上传对象不能为空");
            return result;
        }
        try{
            File materialFile=createDirectoryQuit(rootPath);
            File rootFile=createDirectoryQuit(rootPath+File.separator+root);
            int start=materialFile.getAbsolutePath().length();
            String currentTimeString= DateTime.now().toString("yyyyMMddHHmmss");
            //按月目录
            final String monthPath = currentTimeString.substring(0, 6);
            //按日目录,如W020151111
            final String dayPath = currentTimeString.substring(6, 8);
            final String fileDirectory=rootFile.getAbsolutePath()+"/"+monthPath+"/"+dayPath;
            File saveDirectory=createDirectoryQuit(fileDirectory);
            String originalName = multpFile.getOriginalFilename();
            String uuid= RandomUtil.randomUUID();
            String fileName=uuid;
            String mediaType = "";
            if (originalName.lastIndexOf(".")>0){
                mediaType=multpFile.getOriginalFilename().substring(multpFile.getOriginalFilename().lastIndexOf(".")+1);
                fileName=fileName+"."+mediaType;
            }
            //静态资源存储路径
            StringBuffer storePathBuffer=new StringBuffer();
            String pre=rootFile.getAbsolutePath().substring(start);
            pre= FileUtils.transforSysSpec(pre);
            if (!pre.startsWith("/")){
                storePathBuffer.append("/");
            }
            storePathBuffer.append(pre).append("/").append(monthPath).append("/").append(dayPath).append("/").append(fileName);
            //判断最后一位是否是/
            String invokePath=invokingRoot;
            if (invokingRoot.endsWith("/")){
                invokePath= invokingRoot.substring(0,invokePath.lastIndexOf("/"));
            }
            String url=invokePath+storePathBuffer.toString();
            File targetFile=new File(saveDirectory.getAbsolutePath()+"/"+fileName);
            FileOutputStream fos=new FileOutputStream(targetFile);
            InputStream ins=multpFile.getInputStream();
            byte[] byts=new byte[1024*1024];
            int len=-1;
            while ((len=ins.read(byts))!=-1){
                fos.write(byts,0,len);
            }
            //关闭输入输出流
            fos.close();
            ins.close();
            FileUtils.fileUnModified(targetFile);
            result.put("status","0");
            result.put("msg","上传成功");
            result.put("url",url);
            return result;
        }catch (Exception e){
            result.put("status","1");
            result.put("msg","上传异常");
            return result;
        }
    }

    private File createDirectoryQuit(String path){
        File file=new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        return file;
    }

}
